package com.zxm.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxm.edu.constant.CommonConst;
import com.zxm.edu.dao.CategoryDao;
import com.zxm.edu.dao.CourseDao;
import com.zxm.edu.dao.CourseRecordDao;
import com.zxm.edu.dao.UserInfoDao;
import com.zxm.edu.dto.ArchiveDTO;
import com.zxm.edu.dto.CourseDTO;
import com.zxm.edu.entity.*;
import com.zxm.edu.service.CourseRecordService;
import com.zxm.edu.service.CourseService;
import com.zxm.edu.util.BeanCopyUtils;
import com.zxm.edu.util.PageUtils;
import com.zxm.edu.util.UserUtils;
import com.zxm.edu.vo.ConditionVO;
import com.zxm.edu.vo.CourseVO;
import com.zxm.edu.vo.PageResult;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

import static com.zxm.edu.enums.ArticleStatusEnum.PUBLIC;


/**
 * 课程服务
 *
 * @author silencezheng
 * @date 2022/08/10
 */
@Service
@Slf4j
public class CourseRecordServiceImpl extends ServiceImpl<CourseRecordDao, CourseRecord> implements CourseRecordService {
	@Autowired
	private CourseRecordDao courseRecordDao;
	@Autowired
	private UserInfoDao userInfoDao;

	@Override
	@Transactional
	public Boolean payCourse(CourseRecord courseRecord) {
		courseRecord.setUserId(UserUtils.getLoginUser().getUserInfoId());
		this.saveOrUpdate(courseRecord);
		//更改用户余额
		UserInfo userInfo = userInfoDao.selectById(UserUtils.getLoginUser().getUserInfoId());
		double money = Double.parseDouble(userInfo.getIntro()) - Double.parseDouble(courseRecord.getMoney());
		if (money<0){
			return false;
		}
		userInfoDao.updateById(UserInfo.builder()
				.id(UserUtils.getLoginUser().getUserInfoId())
				.intro(Double.toString(money))
				.build());
		return true;
	}

	@Override
	public Integer listCount(Integer courseId) {
		return courseRecordDao.selectCount(new LambdaQueryWrapper<CourseRecord>()
				.eq(CourseRecord::getCourseId, courseId)
				.eq(CourseRecord::getUserId, UserUtils.getLoginUser().getUserInfoId()));
	}

	@Override
	public PageResult<CourseRecord> list(ConditionVO condition) {
		Page<CourseRecord> page = new Page<>(PageUtils.getCurrent(), PageUtils.getSize());
		// 获取分页数据
		Page<CourseRecord> courseRecordPage = courseRecordDao.selectPage(page, new LambdaQueryWrapper<CourseRecord>()
				.eq(CourseRecord::getUserId, UserUtils.getLoginUser().getUserInfoId()));
		return new PageResult<>(courseRecordPage.getRecords(), (int) courseRecordPage.getTotal());
	}
}
